#!/usr/bin/env python
# -*- coding: utf-8 -*-

''' Stock Market Emulator

@author Kevin Zhang
@email  kevin.misc.10@gmail.com
@date   2011-08-21
'''

import os
import logging
import subprocess
import sys
import time

def main():
    FORMAT = "%(asctime)-15s %(message)s"
    logging.basicConfig(format=FORMAT)
    #logging.basicConfig(stream=1)

    log = logging.getLogger("SME")
    log.warning("MAIN: Start SME(Stock Market Emulator)")

    try:
        p0 = subprocess.Popen(args=["./stockexchange.py"], stdin=None,
                              stdout=None, stderr=None)
        time.sleep(1)
        p1 = subprocess.Popen(args=["./trade.py"], stdin=None,
                              stdout=None, stderr=None)
    except OSError, ValueError:     # How to get e?
        e = ''
        log.warning("MAIN: Popen error %s" % e)
        sys.exit(-1)

    try:
        log.warning("MAIN: Wating for stockexchange.py")
        p0.communicate()
        log.warning("MAIN: stockexchange.py ended")
        log.warning("MAIN: Wating for trade.py")
        p1.communicate()
        log.warning("MAIN: trade.py ended")
    except KeyboardInterrupt, e:
        log.warning("MAIN: Interrupted %s" % e)
        p0.terminate()
        p1.terminate()
    finally:
        log.warning("MAIN: Exit!!!")

if __name__ == '__main__':
    main()

